Page({
  data: {
    // 注释 注释掉自定义导航栏相关数据
    // statusBarHeight: 0,
    // navHeight: 0,
    listData: [],
    isLoading: true,
    targetUserId: null // 存储跳转传入的目标用户ID
  },

  onLoad(options) {
    console.log('【followed页】onLoad：页面加载，传入参数：', options);
    // 注释掉自定义导航栏高度计算代码
    // const systemInfo = wx.getWindowInfo();
    // this.setData({
    //   statusBarHeight: systemInfo.statusBarHeight,
    //   navHeight: systemInfo.statusBarHeight + 44
    // });

    // 从跳转参数中获取目标用户ID
    const { userId } = options;
    if (!userId) {
      wx.showToast({ title: '用户ID无效', icon: 'none' });
      setTimeout(() => wx.navigateBack(), 1500);
      return;
    }
    this.setData({ targetUserId: userId });

    // 校验登录状态并加载数据
    this.checkLoginAndLoadData();
  },

  // 校验登录状态并加载目标用户的关注列表
  checkLoginAndLoadData() {
    const token = wx.getStorageSync('token');
    const userInfo = wx.getStorageSync('userInfo');

    // 处理登录页栈问题
    const pages = getCurrentPages();
    if (pages.length > 1 && pages[pages.length - 1].route === 'pages/login/login') {
      console.log('【followed页】发现登录页在栈顶，尝试关闭');
      wx.navigateBack({ delta: 1 });
    }

    // 未登录时跳转登录（保留目标用户ID，登录后可回传）
    if (!token || !userInfo?.id) {
      console.log('【followed页】未登录，跳转登录页');
      this.setData({ isLoading: false });
      wx.showToast({ title: '请先登录', icon: 'none' });
      setTimeout(() => {
        // 跳转登录时携带目标用户ID，登录后可返回当前页
        wx.redirectTo({ 
          url: `/pages/login/login?redirect=/index/pages/followed/followed&userId=${this.data.targetUserId}` 
        });
      }, 1500);
      return;
    }

    // 登录有效，加载目标用户的关注列表
    this.getFollowList(this.data.targetUserId);
  },

  // 加载关注列表（使用跳转传入的targetUserId）
  getFollowList(followerId) {
    console.log('【followed页】getFollowList：请求列表，目标用户ID=', followerId);
    this.setData({ isLoading: true });
    const token = wx.getStorageSync('token');

    wx.request({
      url: `http://localhost:8080/userr/follow/list/${followerId}`, // 使用目标用户ID
      method: 'GET',
      header: {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json'
      },
      success: (res) => {
        this.setData({ isLoading: false });
        console.log('【followed页】getFollowList：数据返回，页面栈=', getCurrentPages().map(p => p.route));

        if (res.data.code === 200) {
          const formattedData = res.data.data.map(item => ({
            avatar: item.followedUser?.avatarUrl 
              ? `https://gzq123.oss-cn-beijing.aliyuncs.com/${item.followedUser.avatarUrl}` 
              : '/images/default-avatar.png',
            nickname: item.followedUser?.nickname || '未知用户',
            time: item.followedUser?.joinTime 
              ? `${item.followedUser.joinTime.split('-')[0]}年加入` 
              : '未知时间',
            gender: item.followedUser?.sex === 1 ? '男' : '女',
            isFollowed: 1, // 初始为“已关注”（因是“我的关注”列表）
            followedId: item.followedId,
            followRecordId: item.id
          }));
          this.setData({ listData: formattedData });
          console.log('【followed页】数据渲染完成，共', formattedData.length, '条');
        } else if (res.data.code === 401) {
          // Token过期：清除缓存并跳转登录（携带目标ID）
          wx.removeStorageSync('token');
          wx.removeStorageSync('userInfo');
          wx.showToast({ title: '登录已过期', icon: 'none' });
          setTimeout(() => {
            wx.redirectTo({ 
              url: `/pages/login/login?redirect=/index/pages/followed/followed&userId=${this.data.targetUserId}` 
            });
          }, 1500);
        } else {
          wx.showToast({ title: res.data.msg || '获取失败', icon: 'none' });
        }
      },
      fail: () => {
        this.setData({ isLoading: false });
        wx.showToast({ title: '网络错误', icon: 'none' });
      }
    });
  },

  // 关注/取消关注操作
  handleFollow(e) {
    const index = e.currentTarget.dataset.index;
    const listData = [...this.data.listData];
    if (!listData || index < 0 || index >= listData.length) return;

    const currentItem = listData[index];
    const token = wx.getStorageSync('token');
    const userInfo = wx.getStorageSync('userInfo');
    const currentUserId = userInfo?.id;

    if (!token || !currentUserId) {
      wx.showToast({ title: '请先登录', icon: 'none' });
      setTimeout(() => {
        wx.redirectTo({ 
          url: `/pages/login/login?redirect=/index/pages/followed/followed&userId=${this.data.targetUserId}` 
        });
      }, 1500);
      return;
    }

    wx.request({
      url: currentItem.isFollowed === 1 
        ? `http://localhost:8080/userr/follow/cancel`
        : `http://localhost:8080/userr/follow/add`,
      method: 'POST',
      header: {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json'
      },
      data: {
        followerId: currentUserId, // 当前登录用户ID（操作人）
        followedId: currentItem.followedId // 被操作用户ID
      },
      success: (res) => {
        if (res.data.code === 200) {
          currentItem.isFollowed = currentItem.isFollowed === 1 ? 0 : 1;
          this.setData({ listData });
          wx.showToast({
            title: currentItem.isFollowed === 1 ? '关注成功' : '取消关注',
            icon: 'success'
          });
        } else {
          wx.showToast({ title: res.data.msg || '操作失败', icon: 'none' });
        }
      },
      fail: () => wx.showToast({ title: '网络错误', icon: 'none' })
    });
  },

  onShow() {
    console.log('【followed页】onShow：页面显示，页面栈=', getCurrentPages().map(p => p.route));
    const { targetUserId } = this.data;
    if (targetUserId) {
      this.getFollowList(targetUserId); // 刷新目标用户的关注列表
    } else {
      // 若目标ID丢失，尝试从缓存/参数中恢复
      const pages = getCurrentPages();
      const currentPage = pages[pages.length - 1];
      const { userId } = currentPage.options;
      if (userId) {
        this.setData({ targetUserId: userId });
        this.checkLoginAndLoadData();
      } else {
        wx.showToast({ title: '用户ID丢失', icon: 'none' });
        setTimeout(() => wx.navigateBack(), 1500);
      }
    }
  },

  // 跳转用户中心（携带目标用户ID）
  gotoUserCenter(e) {
    const userId = e.currentTarget.dataset.userid;
    console.log('要传递的userId：', userId);
    wx.navigateTo({ url: `/my/pages/user-detail/user-detail?userId=${userId}` });
  },

  // 注释掉自定义导航栏的返回按钮事件（如果使用默认导航栏，无需此方法）
  // onBack() {
  //   wx.navigateBack({ delta: 1 });
  // },

  onPullDownRefresh() {
    const { targetUserId } = this.data;
    if (targetUserId) {
      this.getFollowList(targetUserId);
    }
    wx.stopPullDownRefresh();
  },

  onReady() { console.log('【followed页】onReady：页面就绪'); },
  onHide() { console.log('【followed页】onHide：页面隐藏'); },
  onUnload() { console.log('【followed页】onUnload：页面卸载'); },
  onReachBottom() {},
  onShareAppMessage() {}
})